//
//  TSZEditMricoblog.swift
//  微博天下

import UIKit
import SVProgressHUD
let TSZStatusMaxLenght = 20


class TSZEditMricoblog: UIViewController ,UITextViewDelegate {

    // MARK: 表情键盘控制器
    private lazy var emoticonVc: EmoticonViewController = EmoticonViewController {
        [weak self] (emoticon) ->() in
         self?.textEditView.insertEmoticon(emoticon)
    }
    
    //MARK: 图片选择器
    private lazy var photoSelectorVc: TSZPhotoSeletor = TSZPhotoSeletor()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        addKeyboardOberserver()
    }
    //重写loadView方法
    override func loadView() {
        view = UIView()
        view.backgroundColor = UIColor(white: 1.0, alpha: 1.0)
        
        //按照先后顺序 添加试图
        view.addSubview(textEditView)
        
        view.addSubview(photoSelectorVc.view)
        
        view.addSubview(toolsBar)
        //添加子控件
        addChildViewController(photoSelectorVc)
        
        //准备view都写在这里
        //准备tabBar
        prepareTabBar()
        
        ///准备toolBar
        prepareToolBar()
        
        //准备文本框
        prepareTextView()
        
        //图片选择器
        preparePhotoView()
    }
    
    //MARK: 准备图片选择器
    private func preparePhotoView() {
        //1、自动布局
        var s = UIScreen.mainScreen().bounds.size
        s.height = 0.6 * s.height
        
        photoSelectorVc.view.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: s)
    }
    
    //MARK -选择表情
    func inputEmoticon(){
       //取消第一响应者
        textEditView.resignFirstResponder()
        
        //调出键盘
        textEditView.inputView =  (textEditView.inputView == nil) ?emoticonVc.view : nil
        //键盘成为第一响应者
        textEditView.becomeFirstResponder()
    }
    
    //设置一个全局变量去记录我们的底部约束
    private var toolBarBottom: NSLayoutConstraint?
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textEditView.becomeFirstResponder()
    }
    
    //添加 键盘变化通知  ，注意 监听的name
    func addKeyboardOberserver(){
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification , object: nil)
    }
    //记得  是否放
    deinit {
        removeKeyboardOberserver()
    }
    //删除键盘通知
    private func removeKeyboardOberserver(){
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    // MARK: 键盘通知 变化的方法
    func keyboardChanged(nofify: NSNotification){
        /// 键盘变化监听方法，是由通知中心监听到之后，由运行循环来调度执行，不能设置成 private 的
        //获取目标的frame
        let rect = nofify.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        //动画时长 
        let duration  = nofify.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        //设置约束
        toolBarBottom?.constant = -(UIScreen.mainScreen().bounds.height - rect.origin.y)
        //动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    //MARK - 准备tabBar
    private func prepareTabBar(){
        //左右的item
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "closeEdit")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendMricoblog")
        //使左边的item禁用
        navigationItem.rightBarButtonItem?.enabled = false
        //重新定义view
        
        navigationItem.titleView = tabBarView
    }
    
    ///准备toolBar
    private func prepareToolBar(){
        toolsBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        view.addSubview(toolsBar)
        
        //自动布局
        let icon = toolsBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.size.width, height: 44))
        //记录底部约束
        
        toolBarBottom = toolsBar.ff_Constraint(icon, attribute: NSLayoutAttribute.Bottom)
        
        //定义一个数组
        let itemSettings = [["imageName": "compose_toolbar_picture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background" ,"action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        //定义一个uibarButtonItem
        var items = [UIBarButtonItem]()
        
        //循环添加数组
        for dict in itemSettings {
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, action: dict["action"]))
            //追加一个弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        //移除最后一个弹簧
       items.removeLast()
        toolsBar.items = items
    }
    
    //如果在这里加上private的话就会出现一个访问不了的错误
    func closeEdit(){
        //关闭键盘
        textEditView.resignFirstResponder()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    //MARK: 发送微博
     func sendMricoblog(){
       //检测长度
        let text = textEditView.EmoticonsText
        let textLength  = text.characters.count
        
        if textLength > TSZStatusMaxLenght{
            SVProgressHUD.showInfoWithStatus("输入文本过长！", maskType: SVProgressHUDMaskType.Gradient)
            return
        }
        
        //发布微博
        let image = photoSelectorVc.photos.last
        
        //MARK: 实现联网发送
        TSZNetWorkTools.sharedNetWorkTools.sendMricoblog(text ,image: image) { (result, error) -> () in
            
            if error != nil{
                SVProgressHUD.showErrorWithStatus("网络不给力", maskType: SVProgressHUDMaskType.Gradient)
                return
            }
            
            //保证统一的出口
            self.closeEdit()
        }
    }
    
    //MARK: - 准备文本框
    private func prepareTextView(){
        
//        view.addSubview(textEditView)
        textEditView.backgroundColor = UIColor.whiteColor()
        
        
        //将顶部的导航栏预留出来
//        textEditView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
        
        //自动布局
        textEditView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        
        textEditView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolsBar, size: nil)

        
        //添加占位图像
        placehpldLabel.text = "分享新鲜事..."
        placehpldLabel.sizeToFit()
        textEditView.addSubview(placehpldLabel)
        //自动布局
        placehpldLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: textEditView, size: nil, offset: CGPoint(x: 5, y: 8))
        //MARK: 布局右下角的label
        view.addSubview(tipLabel)
        tipLabel.text = String(TSZStatusMaxLenght)
        
        tipLabel.sizeToFit()
        //使用vh 布局
        tipLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraint(NSLayoutConstraint(item: tipLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 50))
        
        view.addConstraint(NSLayoutConstraint(item: tipLabel, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 32))
        
        view.addConstraint(NSLayoutConstraint(item: tipLabel, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: textEditView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -10))
        view.addConstraint(NSLayoutConstraint(item: tipLabel, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: 0))
        
    }
    //MARK - 懒加载
    
    /// 懒加载一个view
    private lazy var tabBarView: UIView = {
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
//        titleView.backgroundColor = UIColor.cyanColor()
        //添加两个label
        let nameLabel = UILabel(color: UIColor.blackColor(), fontSize: 16)
        nameLabel.text = "发微博"
        nameLabel.sizeToFit()
        titleView.addSubview(nameLabel)
        
        //自动布局
        nameLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        //用户的昵称
        let userName = UILabel(color: UIColor.darkGrayColor(), fontSize: 13)
        userName.text = TSZUserAcountModel.sharedUserAccount()!.name ?? ""
        userName.sizeToFit()
         titleView.addSubview(userName)
        userName.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        return titleView
    }()
    
    //MARK - 懒加载一个toolbar
    private lazy var toolsBar:UIToolbar = UIToolbar()
    
    //懒加载一个textView
    private lazy var textEditView:UITextView   = {
       let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(18)
        //允许垂直拖拽
        tv.alwaysBounceVertical = true
        tv.tintColor = UIColor.blackColor()
        //拖拽关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        //遵守代理
        tv.delegate = self
        return tv
    }()
    
    //占位标签
    private lazy var  placehpldLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 18)

    //MARK: 提示 label
    private lazy var tipLabel: UILabel = {
        let lab = UILabel()
        lab.textColor = UIColor.grayColor()
        lab.font = UIFont.systemFontOfSize(15)
        return lab
    }()
    
    //MARK: textView代理方法
    func textViewDidChange(textView: UITextView) {
        
        placehpldLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        //得到返回的数据
        let text = textEditView.EmoticonsText

        let length = TSZStatusMaxLenght - text.characters.count
        
        //提示用户
        tipLabel.text = "\(length)"
        
        tipLabel.textColor = length < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
    }
    
}
